import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 35000, // 增加到35秒，给后端足够时间
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: false // 明确设置不发送cookie
})

// 创建专门用于认证的axios实例（无需认证）
const authApi = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 35000, // 增加到35秒
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: false
})

// 创建专门用于考试题库的axios实例（无需认证）
const examApi_instance = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 35000, // 增加到35秒
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: false
})

// 为examApi_instance添加请求拦截器（可选认证）
examApi_instance.interceptors.request.use(
  (config) => {
    // 尝试添加认证 token（如果有的话）
    const token = localStorage.getItem('auth_token')
    if (token && !token.startsWith('mock-')) {
      // 只有真实token才添加认证头，模拟token不添加
      config.headers.Authorization = `Token ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 为examApi_instance添加响应拦截器
examApi_instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const { response, request } = error
    
    if (response) {
      switch (response.status) {
        case 400:
          // 400错误通常是表单验证错误
          console.warn('题库API参数错误:', response.data)
          break
          
        case 401:
          // 401错误，可能需要认证，但不强制跳转
          console.warn('题库API需要认证，尝试使用认证API')
          // 不显示错误消息，让上层处理
          break
          
        case 404:
          console.warn('题库API端点不存在:', error.config?.url)
          break
          
        case 500:
          console.error('题库API服务器错误:', response.data)
          break
          
        default:
          console.warn('题库API请求失败:', response.status, response.data?.message || '未知错误')
      }
    } else if (request) {
      console.error('题库API网络连接失败')
    } else {
      console.error('题库API请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证 token
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 认证API响应拦截器（无需token）
authApi.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const { response, request } = error
    
    if (response) {
      switch (response.status) {
        case 400:
          // 400错误通常是表单验证错误，不在这里显示消息
          // 让上层组件处理具体的错误显示
          console.warn('认证API参数错误:', error.config?.url, response.data)
          break
          
        case 404:
          console.warn('认证API端点不存在:', error.config?.url)
          // 只有在非登录/注册页面时才显示错误
          if (!error.config?.url?.includes('/auth/')) {
            ElMessage.error('请求的资源不存在')
          }
          break
          
        case 500:
          ElMessage.error('服务器内部错误')
          break
          
        default:
          console.warn('认证API请求失败:', response.status, response.data?.message || '未知错误')
      }
    } else if (request) {
      console.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const { response, request } = error
    
    if (response) {
      switch (response.status) {
        case 400:
          // 400错误通常是表单验证错误，不在这里显示消息
          // 让上层组件处理具体的错误显示
          console.warn('API参数错误:', error.config?.url, response.data)
          break
          
        case 401:
          // 未授权，清除 token 并跳转到登录页
          localStorage.removeItem('auth_token')
          localStorage.removeItem('user_role')
          router.push('/login')
          ElMessage.error('登录已过期，请重新登录')
          break
          
        case 403:
          ElMessage.error('权限不足')
          break
          
        case 404:
          console.warn('API端点不存在:', error.config?.url)
          // 只对重要的业务API显示错误提示
          if (error.config?.url?.includes('/postings/') || 
              error.config?.url?.includes('/templates/') ||
              error.config?.url?.includes('/applications/') ||
              error.config?.url?.includes('/interviews/')) {
            ElMessage.error('请求的资源不存在')
          }
          break
          
        case 500:
          ElMessage.error('服务器内部错误')
          break
          
        default:
          console.warn('API请求失败:', response.status, response.data?.message || '未知错误')
      }
    } else if (request) {
      console.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 题库相关API
export const examApi = {
  // 获取随机题目
  async getRandomQuestions(total = 10) {
    // 直接使用无认证请求，因为后端已禁用认证要求
    try {
      const response = await examApi_instance.get('/exams/exam/', { params: { total } })
      return response.data
    } catch (error) {
      // 如果无认证失败，尝试带认证请求作为备用
      if (error.response && error.response.status === 401) {
        try {
          const response = await api.get('/exams/exam/', { params: { total } })
          return response
        } catch (authError) {
          // 都失败了，抛出原始错误
          throw error
        }
      }
      
      // 其他错误直接抛出
      throw error
    }
  },
  
  // 获取所有题目（用于题库管理）
  async getAllQuestions() {
    // 先尝试专门的questions端点
    try {
      const response = await examApi_instance.get('/exams/exam/')
      return response.data
    } catch (error) {
      // 备用方案：使用exam端点获取大量题目
      try {
        return await this.getRandomQuestions(100)
      } catch (error2) {
        try {
          return await this.getRandomQuestions(50)
        } catch (error3) {
          return await this.getRandomQuestions(20)
        }
      }
    }
  },
  
  // 根据类型获取题目
  async getQuestionsByType(questionType) {
    try {
      const response = await examApi_instance.get('/exams/exam/', { params: { question_type: questionType } })
      return response.data
    } catch (error) {
      if (error.response && error.response.status === 401) {
        const response = await api.get('/exams/exam/', { params: { question_type: questionType } })
        return response
      }
      throw error
    }
  },
  
  // 根据主题获取题目
  async getQuestionsByTopic(topic) {
    try {
      const response = await examApi_instance.get('/exams/exam/', { params: { topic } })
      return response.data
    } catch (error) {
      if (error.response && error.response.status === 401) {
        const response = await api.get('/exams/exam/', { params: { topic } })
        return response
      }
      throw error
    }
  },
  
  // 创建题目
  createQuestion(questionData) {
    return api.post('/exams/questions/', questionData)
  },
  
  // 更新题目
  updateQuestion(id, questionData) {
    return api.put(`/exams/questions/${id}/`, questionData)
  },
  
  // 删除题目
  deleteQuestion(id) {
    return api.delete(`/exams/questions/${id}/`)
  },
  
  // 获取题目详情
  getQuestionDetail(id) {
    return api.get(`/exams/questions/${id}/`)
  }
}

export default api

// 新的业务API - 包含认证和所有业务功能
export const businessApi = {
  // Auth
  login(credentials) {
    return authApi.post('/auth/login/', credentials);
  },
  register(userData) {
    return authApi.post('/auth/register/', userData);
  },
  logout() {
    return api.post('/auth/logout/');
  },
  getCurrentUser() {
    return api.get('/auth/me/');
  },
  forgotPassword(email) {
    return authApi.post('/auth/forgot-password/', { email });
  },
  resetPassword(token, password) {
    return authApi.post('/auth/reset-password/', { token, password });
  },
  
  // 逻辑题管理 (exams app)
  async getLogistQuestions(page = 1, page_size = 100) {
    try {
      // 首先尝试使用无认证的API
      return await examApi_instance.get(`/exams/logist-questions/?page=${page}&page_size=${page_size}`);
    } catch (error) {
      if (error.response && error.response.status === 401) {
        // 如果401错误，尝试使用认证API
        console.log('尝试使用认证API获取逻辑题');
        return await api.get(`/exams/logist-questions/?page=${page}&page_size=${page_size}`);
      }
      throw error;
    }
  },
  createLogistQuestion(questionData) {
    return api.post('/exams/logist-questions/', questionData);
  },
  updateLogistQuestion(id, questionData) {
    return api.put(`/exams/logist-questions/${id}/`, questionData);
  },
  deleteLogistQuestion(id) {
    return api.delete(`/exams/logist-questions/${id}/`);
  },
  
  // 视频题管理 (spark app)
  async getVideoQuestions(page = 1, page_size = 100) {
    try {
      // 首先尝试使用无认证的API
      return await examApi_instance.get(`/video-questions/?page=${page}&page_size=${page_size}`);
    } catch (error) {
      if (error.response && error.response.status === 401) {
        // 如果401错误，尝试使用认证API
        console.log('尝试使用认证API获取视频题');
        return await api.get(`/video-questions/?page=${page}&page_size=${page_size}`);
      }
      throw error;
    }
  },
  createVideoQuestion(questionData) {
    return api.post('/video-questions/', questionData);
  },
  updateVideoQuestion(id, questionData) {
    return api.put(`/video-questions/${id}/`, questionData);
  },
  deleteVideoQuestion(id) {
    return api.delete(`/video-questions/${id}/`);
  },

  // Job Postings - 职位发布接口
  getJobPostings() {
    return api.get('/postings/');
  },
  getJobPosting(id) {
    return api.get(`/postings/${id}/`);
  },
  createJobPosting(data) {
    return api.post('/postings/', data);
  },
  updateJobPosting(id, data) {
    return api.put(`/postings/${id}/`, data);
  },
  deleteJobPosting(id) {
    return api.delete(`/postings/${id}/`);
  },

  // Interview Templates
  getInterviewTemplates() {
    return api.get('/templates/');
  },
  getInterviewTemplate(id) {
    return api.get(`/templates/${id}/`);
  },
  createInterviewTemplate(data) {
    return api.post('/templates/', data);
  },
  updateInterviewTemplate(id, data) {
    return api.put(`/templates/${id}/`, data);
  },
  deleteInterviewTemplate(id) {
    return api.delete(`/templates/${id}/`);
  },

  // Job Applications - 更新接口路径
  getJobApplications() {
    return api.get('/job-applications/');
  },
  getJobApplication(id) {
    return api.get(`/job-applications/${id}/`);
  },
  createJobApplication(data) {
    return api.post('/job-applications/', data, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
  updateJobApplication(id, data) {
    return api.put(`/job-applications/${id}/`, data);
  },
  deleteJobApplication(id) {
    return api.delete(`/job-applications/${id}/`);
  },

  // Interview Sessions
  getInterviewSessions() {
    return api.get('/sessions/');
  },
  getInterviewSession(id) {
    return api.get(`/sessions/${id}/`);
  },
  createInterviewSession(data) {
    return api.post('/sessions/', data);
  },
  updateInterviewSession(id, data) {
    return api.put(`/sessions/${id}/`, data);
  },
  deleteInterviewSession(id) {
    return api.delete(`/sessions/${id}/`);
  },

  // Interview Results
  getInterviewResults() {
    return api.get('/results/');
  },
  getInterviewResult(id) {
    return api.get(`/results/${id}/`);
  },
  createInterviewResult(data) {
    return api.post('/results/', data);
  },
  updateInterviewResult(id, data) {
    return api.put(`/results/${id}/`, data);
  },

  // 面试详情API
  getInterviewDetail(interviewId) {
    return api.get(`/interviews/${interviewId}/`);
  },

  // 导出 apiClient 以便在组件中直接使用
  apiClient: api
}; 

// 候选人相关API
export const candidateApi = {
  // 查看开放职位列表
  async getOpenJobs() {
    return await api.get('/public/jobs/')
  },

  // 查看职位详情
  async getJobDetail(jobId) {
    return await api.get(`/public/jobs/${jobId}/`)
  },

  // 上传简历申请职位
  async applyForJob(jobId, formData) {
    return await api.post(`/jobs/${jobId}/apply/`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 查看我的申请列表
  async getMyApplications() {
    return await api.get('/my-applications/')
  },

  // 获取申请状态
  async getApplicationStatus(applicationId) {
    return await api.get(`/applications/${applicationId}/status/`)
  }
}

// 面试相关API
export const interviewApi = {
  // 获取简历信息
  async getResumeInfo(applicationId) {
    return await api.get(`/interview/${applicationId}/resume/`)
  },

  // 上传30秒自我介绍视频
  async uploadSelfIntroduction(applicationId, videoFile) {
    const formData = new FormData()
    formData.append('video_file', videoFile)
    
    return await api.post(`/interview/${applicationId}/self-introduction/`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取逻辑思维类题目
  async getLogicQuestions(applicationId) {
    return await api.get(`/interview/${applicationId}/logic-questions/`)
  },

  // 提交逻辑思维类题目答案
  async submitLogicAnswers(applicationId, answers) {
    return await api.post(`/interview/${applicationId}/logic-answers/`, {
      answers
    })
  },

  // 获取指定类别的视频题目
  async getVideoQuestions(applicationId, category) {
    return await api.get(`/interview/${applicationId}/video-questions/${category}/`)
  },

  // 提交视频答案 - 单个视频文件上传
  async submitVideoAnswer(applicationId, category, questionId, videoFile) {
    const formData = new FormData()
    formData.append('question_id', questionId)
    formData.append('video_file', videoFile)
    
    return await api.post(`/interview/${applicationId}/video-answers/${category}/`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 查询面试所有分数结果
  async getInterviewResults(applicationId) {
    return await api.get(`/interview/${applicationId}/results/`)
  },

  // 检查面试状态
  async checkInterviewStatus(applicationId) {
    return await api.get(`/interview/${applicationId}/status/`)
  }
}

// 星火大模型相关API
export const sparkApi = {
  // 提交视频答案并进行AI分析
  async submitVideoAnswerWithAnalysis(applicationId, category, questionId, videoFile) {
    const formData = new FormData()
    formData.append('question_id', questionId)
    formData.append('video_file', videoFile)
    
    return await api.post(`/interview/${applicationId}/video-answers/${category}/`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取面试结果（包含AI分析）
  async getInterviewResults(applicationId) {
    return await api.get(`/interview/${applicationId}/results/`)
  },

  // 生成综合报告
  async generateReport(applicationId) {
    return await api.post(`/interview/${applicationId}/generate-report/`)
  },

  // 检查面试状态
  async checkInterviewStatus(applicationId) {
    return await api.get(`/interview/${applicationId}/status/`)
  }
}

// HR星火大模型相关API
export const hrSparkApi = {
  // 获取报告详情供HR审核
  async getReportDetail(reportId) {
    return await api.get(`/hr/reports/${reportId}/`)
  },

  // HR提交评论和决策
  async submitHRDecision(reportId, decision) {
    return await api.post(`/hr/reports/${reportId}/`, decision)
  },

  // 批量审批
  async batchApproval(reportIds, action, reason) {
    return await api.post(`/hr/reports/batch-approval/`, {
      report_ids: reportIds,
      action,
      reason
    })
  }
}

// HR 面试管理相关API
export const hrApi = {
  // 获取面试管理数据
  async getInterviewManagement(applicationId) {
    return await api.get(`/hr/interview/${applicationId}/management/`)
  },

  // 其他HR相关的接口可以在这里添加
  // ...
} 